package java.Dao.Impl;

import Dao.VerificationCodeDAO;
import entity.VerificationCode;

import java.sql.*;

/**
 * @Author Su
 * @Date 2025/4/29 10:19
 * @Version 1.0 （版本号）
 */
public class VerificationCodeDAOImpl implements VerificationCodeDAO {

    private Connection connection;

    public VerificationCodeDAOImpl(Connection connection) {
        this.connection = connection;
    }

    @Override
    public boolean insertCode(VerificationCode code) throws SQLException {
        String sql = "INSERT INTO verification_code (email, code, type, expire_time) VALUES (?, ?, ?, ?)";
        try (PreparedStatement pstmt = connection.prepareStatement(sql)) {
            pstmt.setString(1, code.getEmail());
            pstmt.setString(2, code.getCode());
            pstmt.setString(3, code.getType());
            pstmt.setTimestamp(4, new Timestamp(code.getExpireTime().getTime()));

            return pstmt.executeUpdate() > 0;
        }
    }

    @Override
    public VerificationCode getValidCode(String email, String code, String type) throws SQLException {
        String sql = "SELECT * FROM verification_code WHERE email = ? AND code = ? AND type = ? AND expire_time > NOW()";
        try (PreparedStatement pstmt = connection.prepareStatement(sql)) {
            pstmt.setString(1, email);
            pstmt.setString(2, code);
            pstmt.setString(3, type);

            try (ResultSet rs = pstmt.executeQuery()) {
                if (rs.next()) {
                    System.out.println("进入了获取验证码");
                    VerificationCode vc = new VerificationCode();
                    vc.setCodeId(rs.getInt("code_id"));
                    vc.setEmail(rs.getString("email"));
                    vc.setCode(rs.getString("code"));
                    vc.setType(rs.getString("type"));
                    vc.setCreateTime(rs.getTimestamp("create_time"));
                    vc.setExpireTime(rs.getTimestamp("expire_time"));
                    return vc;
                }
            }
        }
        return null;
    }

    @Override
    public void deleteExpiredCodes() throws SQLException {
        String sql = "DELETE FROM verification_code WHERE expire_time <= NOW()";
        try (PreparedStatement pstmt = connection.prepareStatement(sql)) {
            pstmt.executeUpdate();
        }
    }
}
